// 导入数据库模块
const { db, readDatabase, writeDatabase } = require('./db');

// 对话历史模型类
class ChatHistoryModel {
  // 获取用户的所有对话历史
  getUserChatHistories(userId) {
    readDatabase();
    const userHistories = db.data.chatHistories.filter(
      history => history.userId === userId
    );
    return userHistories;
  }

  // 获取特定对话历史
  getChatHistoryById(historyId) {
    readDatabase();
    return db.data.chatHistories.find(
      history => history.id === historyId
    );
  }

  // 创建新的对话历史
  createChatHistory(userId, characterId, title = '') {
    readDatabase();
    
    // 创建新对话历史对象
    const newChatHistory = {
      id: db.data.chatHistories.length > 0 ? Math.max(...db.data.chatHistories.map(hist => hist.id)) + 1 : 1,
      userId: userId,
      characterId: characterId,
      title: title,
      messages: [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    // 添加到数据库
    db.data.chatHistories.push(newChatHistory);
    writeDatabase();

    return newChatHistory;
  }

  // 添加消息到对话历史
  addMessageToHistory(historyId, messageData) {
    readDatabase();
    
    const history = db.data.chatHistories.find(
      hist => hist.id === historyId
    );
    
    if (!history) {
      throw new Error('对话历史不存在');
    }

    // 创建新消息对象
    const newMessage = {
      id: history.messages.length > 0 ? Math.max(...history.messages.map(msg => msg.id)) + 1 : 1,
      sender: messageData.sender, // 'user' 或 'character'
      content: messageData.content,
      timestamp: new Date().toISOString(),
      // 可以添加更多字段，如语音消息的URL等
      ...(messageData.voiceUrl && { voiceUrl: messageData.voiceUrl })
    };

    // 添加消息到对话历史
    history.messages.push(newMessage);
    history.updatedAt = new Date().toISOString();

    // 如果没有标题或需要更新标题（例如使用第一条消息内容）
    if (!history.title || messageData.updateTitle) {
      history.title = messageData.content.substring(0, 50) + (messageData.content.length > 50 ? '...' : '');
    }

    // 保存更新
    writeDatabase();

    return newMessage;
  }

  // 更新对话历史标题
  updateChatHistoryTitle(historyId, title) {
    readDatabase();
    
    const history = db.data.chatHistories.find(
      hist => hist.id === historyId
    );
    
    if (!history) {
      throw new Error('对话历史不存在');
    }

    // 更新标题
    history.title = title;
    history.updatedAt = new Date().toISOString();

    // 保存更新
    writeDatabase();

    return history;
  }

  // 删除对话历史
  deleteChatHistory(historyId) {
    readDatabase();
    
    const historyIndex = db.data.chatHistories.findIndex(
      hist => hist.id === historyId
    );
    
    if (historyIndex === -1) {
      throw new Error('对话历史不存在');
    }

    // 删除对话历史
    const deletedHistory = db.data.chatHistories.splice(historyIndex, 1)[0];
    writeDatabase();

    return deletedHistory;
  }

  // 清空对话历史中的消息
  clearChatHistoryMessages(historyId) {
    readDatabase();
    
    const history = db.data.chatHistories.find(
      hist => hist.id === historyId
    );
    
    if (!history) {
      throw new Error('对话历史不存在');
    }

    // 清空消息数组
    history.messages = [];
    history.updatedAt = new Date().toISOString();

    // 保存更新
    writeDatabase();

    return history;
  }

  // 获取角色的对话历史数量
  getCharacterChatCount(characterId) {
    readDatabase();
    return db.data.chatHistories.filter(
      history => history.characterId === characterId
    ).length;
  }
}

// 导出对话历史模型实例
module.exports = new ChatHistoryModel();